var express = require('express');
var router = express.Router();
var mongoose = require('mongoose');

mongoose.connect('mongodb://www.imshow.vip/db_job', { useMongoClient : true });
const jobSchema = mongoose.Schema({
  name : String,
  age : String
});
const  Job = mongoose.model('job', jobSchema);

function getDbCollection(){
  return db.collection(collection);
}

//添加
router.post('/', function (req, res) { 
  var job = new Job(req.body);//创建一个实例
  //保存方法，保存实例进入到数据库中
  job.save(function (err) {
    if (err) {
      res.json({ state: false, msg: "添加失败" });
    } else {
      res.json({state:true,msg:"添加成功"});
    }
  }); 
});

//修改
router.put('/:id', function (req, res) { 
  var update = { $set: { name: req.body.name, age: req.body.age } };
  var options = { upsert: true };
  Job.update({ _id: req.params.id }, update, options, function (err) {
    if (err) {
      res.json({ state: false, msg: "修改失败" });
    } else {
      res.json({ state: true, msg: "修改成功" });
    }
  });
});

//删除
router.delete('/:id', function (req, res) {  
  //var job = new Job({ _id: req.params.id });//创建一个实例
  Job.remove({ _id: req.params.id },function(err,doc){
        if(err){
          res.json({ state: false });
        }else{
          res.json({ state: true})
        }
    });
 
});

router.get('/', function (req, res) {
  var curr = req.params.curPage;
  var pageSize = req.params.pageSize;
  if (curr == undefined) {
    curr = 1
  }
  if (pageSize == undefined) {
    pageSize = 10
  }
  var query = Job.find({});
  query.skip((curr - 1) * pageSize);
  query.limit(pageSize);
  query.exec(function (err, rs) {
    if (err) {
      res.send(err);
    } else {
      Job.find(function (err, result) {
        pageCount = Math.ceil(result.length / pageSize);        
        rsList = { data: rs, pageCount: pageCount, pageSize: pageSize };
        res.json(rsList);
      });
    }
  });
});

module.exports = router;
